<template>
  <div class="selector-wrap">
    <div>
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-table
      :data="filteredData"
      highlight-current-row
      :row-class-name="tableRowClassName"
      @current-change="handleCurrentChange"
    >
      <el-table-column width="55" align="center" />
      <el-table-column label="合同名称" prop="contractName" min-width="200" />
      <el-table-column label="负责人" prop="majorUsername" />
      <el-table-column label="状态" prop="status" width="150">
        <template #default="scope">
          <el-tag v-if="scope.row.status" type="success">
            {{ ContractBuild_Status_Label[scope.row.status] }}
          </el-tag>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-if="total > 0"
      v-model:total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="handleQuery"
    />
  </div>
</template>

<script setup lang="ts">
import { defineProps, defineEmits } from "vue";
import BuildAPI, {
  BuildPageQuery,
  BuildPageVO,
  ContractBuild_Status_Label,
} from "@/api/flow/build.api";

const props = defineProps({
  modelValue: {
    type: Array,
    default: () => [],
  },
  // 查询参数
  exQuery: {
    type: Object,
    default: () => ({}),
  },
});

const emit = defineEmits(["update:modelValue", "selection-change"]);

const total = ref(0); // 总数
const filteredData = ref<BuildPageVO[]>(); // 过滤后的数据
const checked = ref<BuildPageVO>(); // 已选择的数据
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
}) as BuildPageQuery;

const handleCurrentChange = (selection: BuildPageVO) => {
  checked.value = selection;
};

function getChecked(): BuildPageVO | undefined {
  return checked.value;
}
const handleQuery = () => {
  Object.assign(queryParams, props.exQuery);
  BuildAPI.loadOwn(queryParams).then((data) => {
    filteredData.value = data.list;
    total.value = data.total;
  });
};

const handleResetQuery = () => {
  queryParams.keywords = "";
  queryParams.pageNum = 1;
  handleQuery();
};

// 行样式
const tableRowClassName = ({ row }: { row: BuildPageVO }) => {
  if (row.id === checked.value?.id) {
    return "checked-row";
  }
  return "";
};

defineExpose({
  getChecked,
  handleQuery,
});
</script>

<style scoped>
.selector-wrap {
  padding: 10px;
}
</style>
